package com.zzxx.controller;

import com.zzxx.entity.User;
import com.zzxx.entity.UserAndCoupons;
import com.zzxx.exceptions.LoginException;
import com.zzxx.service.UserService;
import com.zzxx.utils.EncryptUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Map;

@Controller
@RequestMapping("user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private HttpServletResponse response;
    @RequestMapping("sendEmail")
    @ResponseBody
    public String sendEmail(String email){
        System.out.println(email);
        String  code= null;
        try {
            code = userService.send(email);
        } catch (LoginException e) {
          return e.getMessage();
        }
        return code;
    }
    @RequestMapping("register")
    @ResponseBody
    public String register(@RequestBody User user) throws Exception {
        user.setPassword(EncryptUtil.md5Encode(user.getPassword()));
        try {
            userService.register(user);
        } catch (LoginException e) {
            return e.getMessage();
        }
        return "succeed";
    }
    @RequestMapping("login")
    @ResponseBody
    public String login(@RequestBody Map<String,Object> map) throws Exception {
        Map loginUser = (Map)map.get("loginUser");
        String username = (String) loginUser.get("username");
        String password = (String) loginUser.get("password");
        password = EncryptUtil.md5Encode(password);
        String autoLogin = loginUser.get("autoLogin").toString();
        try {
            User user= userService.findUser(username,password);
            request.getSession().setAttribute("loginUser",user);
            if(!"".equals(autoLogin)){
                Cookie userCookie=new Cookie("username",username);
                Cookie pwdCookie = new Cookie("password", password);
                userCookie.setMaxAge(7*24*60*60);
                pwdCookie.setMaxAge(7*24*60*60);
                userCookie.setPath(request.getContextPath());
                pwdCookie.setPath(request.getContextPath());
                response.addCookie(userCookie);
                response.addCookie(pwdCookie);
            }
        }catch (LoginException e){
            return e.getMessage();
        }
        return "succeed";
    }

    @ResponseBody
    @RequestMapping(value = "findLogin", method = RequestMethod.GET)
    public User findLogin() throws LoginException {
        User loginUser = (User) request.getSession().getAttribute("loginUser");
        User user= userService.findUser(loginUser.getUsername(),loginUser.getPassword());
        request.getSession().setAttribute("loginUser",user);
        return user;
    }

    @ResponseBody
    @RequestMapping(value = "findLogin/{tid}", method = RequestMethod.GET)
    public UserAndCoupons findLogin(@PathVariable("tid") String tid){
        UserAndCoupons uac = new UserAndCoupons();
        User loginUser = (User) request.getSession().getAttribute("loginUser");
        if (tid==null||loginUser==null) return null;
        uac.setLoginUser(loginUser);
        userService.packageUserAndCoupons(uac, tid);
        return uac;
    }


    @RequestMapping("active")
    public String active( String id){
     boolean flag=userService.active(id);
     if(flag){
         return "redirect:/userclient/login.html";
     }else {
        return  "redirect:/userclient/index.html";
     }
    }

    @ResponseBody
    @RequestMapping("find/{id}")
    public User findById(@PathVariable("id") String id){
        User user = userService.findById(id);
        User loginUser = (User) request.getSession().getAttribute("loginUser");
        if (loginUser==null||!user.getId().equals(loginUser.getId())) return null;
        //更新一下登录用户信息
        request.getSession().setAttribute("loginUser",user);
        return user;
    }
    @RequestMapping(value = "photo", method = RequestMethod.POST)
    public String photo(MultipartFile photoFile){
        User loginUser = (User)request.getSession().getAttribute("loginUser");
        String uid=loginUser.getId();
        String originalFilename = photoFile.getOriginalFilename();
        String last = originalFilename.substring(originalFilename.lastIndexOf("."));
        //判断上传的是否是jpg格式，如果上传的不是jpg图片则产生异常
        if(!".jpg".equals(last)){
            return "redirect:/userclient/personInfo.html?msg=noPhoto&id="+uid;
        }
        try {
            userService.loadPhoto(photoFile);
            return "redirect:/userclient/personInfo.html?msg=success&id="+uid;
        }catch (LoginException e){
            return "redirect:/userclient/personInfo.html?msg="+e.getMessage()+"&id"+uid;
        }catch (Exception e){
            return "redirect:/userclient/personInfo.html?msg=fail&id="+uid;
        }
    }
    @RequestMapping("outLogin")
    @ResponseBody
    public String outLogin(){
        HttpSession session = request.getSession();
        session.invalidate();
        String username=null;
        String password=null;
        Cookie[] cookies = request.getCookies();
        if(cookies!=null){
            for(Cookie c:cookies){
                if(c.getName().equals("username")){
                    username=c.getValue();
                }
                if(c.getName().equals("password")){
                    password=c.getValue();
                }
            }
        }
        Cookie cookie1 = new Cookie("username",username );
        Cookie cookie2 =new Cookie("password",password);
        cookie1.setPath(request.getContextPath());
        cookie2.setPath(request.getContextPath());
        cookie1.setMaxAge(0);
        cookie2.setMaxAge(0);
        response.addCookie(cookie1);
        response.addCookie(cookie2);
        return "success";
    }
    @RequestMapping(value = "updateMoney",method = RequestMethod.POST)
    @ResponseBody
    public void updateMoney(@RequestBody Map<String,User> map){
        userService.updateMoney(map.get("user"));
        System.out.println("进来了");

    }
}
